package com.logos.controller;

import com.logos.common.Result;
import com.logos.common.ResultCode;
import com.logos.entity.Book;
import com.logos.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping
    public Result insert(@RequestBody Book book) {
        boolean flag = bookService.insert(book);
        return new Result(flag? ResultCode.SAVE_OK: ResultCode.SAVE_ERR,flag);
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        return new Result(flag? ResultCode.UPDATE_OK: ResultCode.UPDATE_ERR,flag);
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        boolean flag = bookService.deleteById(id);
        return new Result(flag? ResultCode.DELETE_OK: ResultCode.DELETE_ERR,flag);
    }

    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id) {
        Book book = bookService.selectById(id);
        Integer code = book != null?ResultCode.GET_OK: ResultCode.GET_ERR;
        String msg = book != null?"success":"fail";
        return new Result(code,book,msg);
    }

    @GetMapping
    public Result selectAll() {
        List<Book> bookList = bookService.selectAll();
        Integer code = bookList != null?ResultCode.GET_OK: ResultCode.GET_ERR;
        String msg = bookList != null?"success":"fail";
        return new Result(code,bookList,msg);
    }
}
